import React, { useState, useEffect } from "react";

// 自定义Hook，外部操作，内部执行
function useCounter(initialCount) {
  // 计数
  const [count, setCount] = useState(initialCount);
  // 是否暂停
  const [pause, setPause] = useState(false);
  useEffect(() => {
    const timer = setTimeout(() => {
      // 如果没有暂停，计数+1
      !pause && setCount(count + 1);
    }, 1000);

    // 组件小灰灰前和更新前，清理timer
    return () => {
      clearTimeout(timer);
    };
    // 所有要用的变量需要放到监听依赖列表
  }, [count, pause]);

  // 重置计数
  const reset = () => {
    setCount(initialCount);
  };

  // 暂停或启动
  const toggle = () => {
    setPause(!pause);
  };

  // 把需要用的变量或函数作为函数的返回值(API)
  return [count, reset, toggle];
}

function TimerHook() {
  // 复用目的
  const [count1, resetCount1, toggle1] = useCounter(1);
  const [count2, resetCount2, toggle2] = useCounter(10);

  return (
    <>
      <div>
        <div>计数器</div>
        <h3>{count1}</h3>
        <button onClick={resetCount1}>Reset-1</button>
        <button onClick={toggle1}>pause-1</button>
        <h3>{count2}</h3>
        <button onClick={resetCount2}>Reset-2</button>
        <button onClick={toggle2}>pause-2</button>
      </div>
    </>
  );
}

export default TimerHook;
